package com.tasly.attendance.util;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AttendanceUtils {
    
    private static final Map<String, String> ID_2_PERSON_MAP = new HashMap<String, String>();
    
    static {
        Properties properties = new Properties();
        try {
            //use below when debug
//            properties.load(new FileReader(new File(System.getProperty("user.dir")+"/src/com/tasly/attendance/config/id2person.properties")));
            //use below when release
            properties.load(AttendanceUtils.class.getResourceAsStream("/com/tasly/attendance/config/id2person.properties"));
        } catch (Exception e) {
            System.out.println("Exception occurred when try to load id2person properties file!!");
        }
        
        convertProp2Map(properties);
    }

    private AttendanceUtils() {
        throw new Error("DO NOT instance me!!");
    }

    // make this configurable
    // check whether start with numberic or not
    private static final String VALIDATE_RULE_STR = "^\\d.*$";

    public static boolean validateIncomingLine(String line) {
        Pattern pattern = Pattern.compile(VALIDATE_RULE_STR);
        Matcher matcher = pattern.matcher(line);
        return matcher.matches();
    }
    
    public static Date getNextDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }
    
    public static double calculateInterval(Date startTime, Date endTime) {
      double workingHours = (endTime.getTime() - startTime.getTime())/(60*60*1000);
      return workingHours;
    }
    
    private static void convertProp2Map(Properties properties){
        Set<Object> ids = properties.keySet();
        String key;
        for (Object object : ids) {
            if (object instanceof String) {
                key = (String)object;
                ID_2_PERSON_MAP.put(key, properties.getProperty(key));
            }
        }
    }
    
    public static Map<String, String> getId2PersoMap() {
        return ID_2_PERSON_MAP;
    }
}
